﻿using AutoMapper;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 职位信息
    /// </summary>
    public class JobServices:IJobServices
    {
        private readonly IBaseRepository<JobModel> _Job;
        private readonly IBaseRepository<EMPModel> _Emp;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Job"></param>
        /// <param name="EmpModel"></param>
        /// <param name="mapper"></param>
        public JobServices(IBaseRepository<JobModel> Job, IBaseRepository<EMPModel> EmpModel, IMapper mapper)
        {
            _Job = Job;
            _Emp = EmpModel;
            this._mapper = mapper;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="Job"></param>
        /// <returns></returns>
        public ApiResult<int> AddJob(JobModel Job)
        {
            try
            {
                //判断职位编码，名称是否为空
                if (string.IsNullOrEmpty(Job.JobId) || string.IsNullOrEmpty(Job.JobName))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查职位编码，名称是否为空"
                    };
                }
                var model = _Job.GetValue(x => x.JobId == Job.JobId);
                if (model != null && !string.IsNullOrEmpty(model.JobId))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "职位编号重复，请重新检查修改！！！"
                    };
                }
                //添加
                var models = _mapper.Map<JobModel>(Job);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = _Job.Add(Job),
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加职位时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }


        ///// <summary>
        ///// 查询
        ///// </summary>
        ///// <param name="qryInput"></param>
        ///// <returns></returns>
        //public ApiResult<List<JobOut>> GetJob(QryInput qryInput)
        //{
        //    try
        //    {
        //        int totalCount = 0;

        //        // 获取所有库位
        //        var list = _Job.GetAll().Where(x => x.IsDeleted == false);


        //        if (qryInput.PageSize == 0)
        //        {

        //            list = list.OrderBy(u => u.CreatedTime).Where(x => x.IsEnable == true);
        //        }
        //        else
        //        {

        //            // 按编码查询
        //            if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
        //            {
        //                list = list.Where(x => x.JobId.Contains(qryInput.QryID) && x.JobName.Contains(qryInput.QryName));
        //            }
        //            else if (!string.IsNullOrEmpty(qryInput.QryID))
        //            {
        //                list = list.Where(x => x.JobId.Contains(qryInput.QryID));
        //            }
        //            else if (!string.IsNullOrEmpty(qryInput.QryName))
        //            {
        //                list = list.Where(x => x.JobName.Contains(qryInput.QryName));
        //            }


        //        }
        //        // 处理结果数据
        //        var result = new List<JobOut>();

        //        //链表查询
        //        var query1 = list.LeftJoin<DEPModel>((a, b) => a.DepId == b.DepId).LeftJoin<JobOut>((a, b,c) => a.SuperiorJobID == c.DepId).Select((a, b) =>
        //            new JobOut
        //            {
        //                DepId=b.DepId,
        //                JobId=a.JobId,
        //                JobName=a.JobName,
        //                DepName=b.DepName,
        //                SuperiorJobID=a.DepId,
        //                SuperiorJobName=a.JobName,
        //                CreatedBy = a.CreatedBy,
        //                CreatedTime = a.CreatedTime,
        //                UpdatedTime = a.UpdatedTime,
        //                IsDeleted = a.IsDeleted,
        //                IsEnable = a.IsEnable
        //            });

        //        //获取集合
        //        var queryList = query1?.ToList();



        //        return new ApiResult<List<JobOut>>()
        //        {
        //            Code = ApiEnums.Success,
        //            Message = "查询成功",
        //            Data = queryList,
        //            TotalCount = queryList.Count(),
        //            PageNum = qryInput.PageNum,
        //            PageSize = qryInput.PageSize
        //        };

        //    }
        //    catch (Exception ex)
        //    {
        //        // 记录异常信息
        //        Console.WriteLine($"查询职位时发生异常: {ex.Message}");

        //        return new ApiResult<List<JobOut>>()
        //        {
        //            Code = ApiEnums.Fail,
        //            Message = $"查询失败: {ex.Message}",
        //            Data = new List<JobOut>(),
        //            TotalCount = 0
        //        };
        //    }
        //}

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="qryInput"></param>
        /// <returns></returns>
        public ApiResult<List<JobOut>> GetJob(string DepId)
        {
            try
            {
                int totalCount = 0;

                // 获取所有库位
                var list = _Job.GetAll().Where(x => x.IsDeleted == false);


                //if (qryInput.PageSize == 0)
                //{

                //    list = list.OrderBy(u => u.CreatedTime).Where(x => x.IsEnable == true);
                //}
                //else
                //{

                //    // 按编码查询
                //    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                //    {
                //        list = list.Where(x => x.JobId.Contains(qryInput.QryID) && x.JobName.Contains(qryInput.QryName));
                //    }
                //    else if (!string.IsNullOrEmpty(qryInput.QryID))
                //    {
                //        list = list.Where(x => x.JobId.Contains(qryInput.QryID));
                //    }
                //    else if (!string.IsNullOrEmpty(qryInput.QryName))
                //    {
                //        list = list.Where(x => x.JobName.Contains(qryInput.QryName));
                //    }


                //}
                list = list.Where(x => x.DepId==DepId);
                // 处理结果数据
                var result = new List<JobOut>();

                //链表查询
                var query1 = list.LeftJoin<DEPModel>((a, b) => a.DepId == b.DepId).LeftJoin<JobModel>((a, b, c) => a.SuperiorJobID == c.DepId).Select((a, b,c) =>
                    new JobOut
                    {
                        DepId = b.DepId,
                        JobId = a.JobId,
                        JobName = a.JobName,
                        DepName = b.DepName,
                        SuperiorJobID = a.SuperiorJobID,
                        SuperiorJobName = c.JobName,
                        CreatedBy = a.CreatedBy,
                        CreatedTime = a.CreatedTime,
                        UpdatedTime = a.UpdatedTime,
                        IsDeleted = a.IsDeleted,
                        IsEnable = a.IsEnable,
                        RankOrder=a.RankOrder
                    });

                //获取集合
                var queryList = query1?.ToList();



                return new ApiResult<List<JobOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = queryList.Count(),
                    PageNum = 0,
                    PageSize =0
                };

            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询职位时发生异常: {ex.Message}");

                return new ApiResult<List<JobOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<JobOut>(),
                    TotalCount = 0
                };
            }
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="JobId"></param>
        /// <returns></returns>
        public ApiResult<JobOut> GetJobById(string JobId)
        {
            try
            {
                // 获取所有库位
                var list = _Job.GetAll().Where(x => x.IsDeleted == false);

                list = list.Where(x => x.JobId == JobId);
               
                //链表查询
                var query1 = list.LeftJoin<DEPModel>((a, b) => a.DepId == b.DepId).LeftJoin<JobModel>((a, b, c) => a.SuperiorJobID == c.DepId).Select((a, b, c) =>
                    new JobOut
                    {
                        DepId = b.DepId,
                        JobId = a.JobId,
                        JobName = a.JobName,
                        DepName = b.DepName,
                        SuperiorJobID = a.SuperiorJobID,
                        SuperiorJobName = c.JobName,
                        CreatedBy = a.CreatedBy,
                        CreatedTime = a.CreatedTime,
                        UpdatedTime = a.UpdatedTime,
                        IsDeleted = a.IsDeleted,
                        IsEnable = a.IsEnable,
                        RankOrder = a.RankOrder
                    });

                //获取集合
                //var queryList = query1?.ToList();



                return new ApiResult<JobOut>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = query1.First()
                };

            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询职位时发生异常: {ex.Message}");

                return new ApiResult<JobOut>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new JobOut()
                };
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateJob(JobModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _Job.GetValue(x => x.JobId == model.JobId);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的职位信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                //保存添加人和添加时间，添加修改人和修改时间
                _Job.Update(model);

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改职位时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(JobModel model)
        {
            var IsEnable = model.IsEnable;
            //根据id修改逻辑删除为 false
            model = _Job.GetValue(x => x.JobId == model.JobId);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _Job.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(string Id)
        {
            //根据id修改逻辑删除为 false
            var model = _Job.GetValue(x => x.JobId == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _Job.Delete(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="JobId"></param>
        /// <returns></returns>
        public ApiResult<int> GetJobId(string JobId)
        {
            var model = _Job.GetValue(x => x.JobId == JobId);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
